from aiogram import Bot, Dispatcher, types, F
from dotenv import load_dotenv
import os
import asyncio
import logging
# from models.model import get_users, init, get_user, create_user

from aiogram.filters import CommandStart, Command
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, Message, ContentType
from icecream import ic
from models.model import Cities, User, init
from tortoise import Tortoise
from handlers import weather_settings
from my_services import coordinates
from datetime import datetime, timedelta
from typing import Callable

load_dotenv()


token = os.getenv('TG_TOKEN')
dp = Dispatcher()

ic.disable()


user_range = {
    
}

async def ten_minuts(bot: Bot, user_id: int, step: int, cities: str) -> None:
    now = datetime.now()
    send_times = [10, 14, 18]
    current_hour = now.hour
    if user_range.get(user_id) is None:
        ic('Нет в словаре!')
        next_hour = min(send_times, key=lambda x: (x - current_hour) % 24)
        user_range[user_id] = {
            'last_range': datetime.now(),
            'next_range': ic(next_hour),
        }
    last_range = user_range[user_id]['last_range']
    time_passed_minutes = (now - last_range).total_seconds() / 60
    ic(time_passed_minutes)
    if time_passed_minutes >= ic(float(step)):
        text = await coordinates(cities)
        user_range[user_id]['last_range'] = now
        
        await bot.send_message(user_id, text)



async def five_minuts(bot: Bot, user_id: int, step: int, cities: str) -> None:
    send_times = [10, 14, 18]
    now = datetime.now()
    current_hour = now.hour
    if user_range.get(user_id) is None:
        next_hour = min(send_times, key=lambda x: (x - current_hour) % 24)
        user_range[user_id] = {
            'next_range': ic(next_hour),
            'last_range': datetime.now()
        }
    next_hour = user_range[user_id]['next_range']
    if current_hour == ic(next_hour):
        next_hour = min(send_times, key=lambda x: (x - current_hour) % 24)
        user_range[user_id]['next_range'] = next_hour
        text = await coordinates(cities)
        await bot.send_message(user_id, text)
    # # Проверяем, наступил ли один из часов отправки
    # if current_hour in send_times and now.minute == 0:
    #     text = await coordinates(cities)
    #     await bot.send_message(user_id, text)
    #     # Ждем до следующего часа, чтобы избежать повторной отправки в этот же час
    #     sleep_seconds = 3600 - now.minute * 60 - now.second
    # else:
    #     # Ждем одну минуту до следующей проверки
    #     sleep_seconds = 60
    # return sleep_seconds
    

async def send_user(bot: Bot):
    while True:
        now = datetime.now()
        users = await User.all()
        sleep_seconds = 10       
        for user in users:

            cities = await Cities.get_or_none(user=user)
            if cities:
                actions = {
                    '10': lambda: ten_minuts(bot, user.tg_id, 10, cities.citie),
                    '30': lambda: ten_minuts(bot, user.tg_id, 30, cities.citie),
                    '5': lambda: five_minuts(bot, user.tg_id, 1, cities.citie)
                }
                if user.range in actions.keys():
                    await actions[user.range]()
                await asyncio.sleep(sleep_seconds)
            else:
                await asyncio.sleep(5)  # Краткая пауза перед следующей проверкой, если город не найден    


async def main():
    await init()
    bot = Bot(token=token, parse_mode='HTML')
    logging.basicConfig(level=logging.INFO)
    dp.include_router(weather_settings.router)
    await bot.send_message(453994951, "Bot started")
    asyncio.create_task(send_user(bot))
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot)
    await Tortoise.close_connections()
    


if __name__ in '__main__':
    asyncio.run(main())
